<script setup>
import { ref, computed } from 'vue'
import { useCanvasStore } from '@/stores/canvas'
import { getComponentTemplate } from '@/config/components'
import { v4 as uuidv4 } from 'uuid'
import RenderComponent from './RenderComponent.vue'

const canvasStore = useCanvasStore()
const canvasRef = ref()

// 计算属性
const components = computed(() => canvasStore.canvasState.components)
const selectedComponentIds = computed(() => canvasStore.canvasState.selectedComponentIds)

// 框选相关状态
const isDragging = ref(false)
const isSelecting = ref(false)
const selectionBox = ref({
    startX: 0,
    startY: 0,
    currentX: 0,
    currentY: 0
})

// 处理拖拽放置
const handleDrop = (event) => {
    event.preventDefault()

    try {
        const dragData = JSON.parse(event.dataTransfer.getData('application/json'))

        if (dragData.type === 'component') {
            // 获取放置位置
            const rect = canvasRef.value.getBoundingClientRect()
            const x = event.clientX - rect.left
            const y = event.clientY - rect.top

            // 获取组件模板
            const template = getComponentTemplate(dragData.componentType)
            if (!template) return

            // 创建新组件
            const newComponent = {
                id: uuidv4(),
                type: template.type,
                props: { ...template.defaultProps },
                style: {
                    ...template.defaultStyle,
                    position: 'absolute',
                    left: `${x}px`,
                    top: `${y}px`,
                    zIndex: '1'
                },
                position: { x, y },
                size: {
                    width: parseInt(template.defaultStyle?.width || '100'),
                    height: parseInt(template.defaultStyle?.height || '32')
                }
            }

            canvasStore.addComponent(newComponent)
        }
    } catch (error) {
        console.error('Drop error:', error)
    }
}

// 处理拖拽悬停
const handleDragOver = (event) => {
    event.preventDefault()
    event.dataTransfer.dropEffect = 'copy'
}

// 处理组件选中
const handleComponentClick = (componentId, event) => {
    event.stopPropagation()
    const isCtrlPressed = event.ctrlKey || event.metaKey
    
    // 如果当前组件已经被选中且是 Ctrl 多选的一部分，不要改变选中状态
    // 这样可以避免拖动多选组件时失去选中状态
    if (!isCtrlPressed && selectedComponentIds.value.includes(componentId) && selectedComponentIds.value.length > 1) {
        // 当前组件是多选的一部分，不改变选中状态
        return
    }
    console.log('触发组件 click 事件', componentId, isCtrlPressed)
    canvasStore.selectComponent(componentId, isCtrlPressed)
}

// 处理画布点击（取消选中）
const handleCanvasClick = (event) => {
    // 只有直接点击画布时才取消选中
    if (event.target === canvasRef.value && !isDragging.value) {
        canvasStore.selectComponent(null)
    }
}

// 框选功能 - 开始框选
const handleMouseDown = (event) => {
    // 只有直接点击画布才触发框选
    isDragging.value = false
    if (event.target !== canvasRef.value) return
    
    const rect = canvasRef.value.getBoundingClientRect()
    isSelecting.value = true
    selectionBox.value = {
        startX: event.clientX - rect.left,
        startY: event.clientY - rect.top,
        currentX: event.clientX - rect.left,
        currentY: event.clientY - rect.top
    }
}

// 框选功能 - 拖动框选
const handleMouseMove = (event) => {
    isDragging.value = true
    if (!isSelecting.value) return
    
    const rect = canvasRef.value.getBoundingClientRect()
    selectionBox.value.currentX = event.clientX - rect.left
    selectionBox.value.currentY = event.clientY - rect.top
    
    // 计算框选范围内的组件
    updateSelectedComponents()
}

// 框选功能 - 结束框选
const handleMouseUp = (event) => {
    if (isSelecting.value) {
        updateSelectedComponents()
        isSelecting.value = false
    }
}

// 更新选中的组件（根据框选范围）
const updateSelectedComponents = () => {
    const box = selectionBox.value
    const minX = Math.min(box.startX, box.currentX)
    const maxX = Math.max(box.startX, box.currentX)
    const minY = Math.min(box.startY, box.currentY)
    const maxY = Math.max(box.startY, box.currentY)
    
    // 查找在框选范围内的组件
    const selectedIds = components.value.filter(comp => {
        const compX = comp.position?.x || 0
        const compY = comp.position?.y || 0
        const compWidth = comp.size?.width || 100
        const compHeight = comp.size?.height || 32
        
        // 判断组件是否与框选区域相交
        return !(compX > maxX || compX + compWidth < minX || 
                 compY > maxY || compY + compHeight < minY)
    }).map(comp => comp.id)
    
    if (selectedIds.length > 0) {
        canvasStore.selectMultipleComponents(selectedIds)
    } else {
        canvasStore.selectComponent(null)
    }
}

// 计算框选框的样式
const selectionBoxStyle = computed(() => {
    if (!isSelecting.value) return { display: 'none' }
    
    const box = selectionBox.value
    const left = Math.min(box.startX, box.currentX)
    const top = Math.min(box.startY, box.currentY)
    const width = Math.abs(box.currentX - box.startX)
    const height = Math.abs(box.currentY - box.startY)
    
    return {
        position: 'absolute',
        left: `${left}px`,
        top: `${top}px`,
        width: `${width}px`,
        height: `${height}px`,
        border: '2px dashed #3b82f6',
        backgroundColor: 'rgba(59, 130, 246, 0.1)',
        pointerEvents: 'none',
        zIndex: 9999
    }
})

// 处理组件移动
const handleComponentMove = (componentId, position) => {
    // 如果有多个组件被选中，同时移动所有选中的组件
    if (selectedComponentIds.value.length > 1 && selectedComponentIds.value.includes(componentId)) {
        // 计算移动的偏移量
        const currentComponent = canvasStore.canvasState.components.find(c => c.id === componentId)
        if (currentComponent) {
            const deltaX = position.x - (currentComponent.position?.x || 0)
            const deltaY = position.y - (currentComponent.position?.y || 0)
            
            // 移动所有选中的组件
            selectedComponentIds.value.forEach(id => {
                const comp = canvasStore.canvasState.components.find(c => c.id === id)
                if (comp) {
                    const newPos = {
                        x: (comp.position?.x || 0) + deltaX,
                        y: (comp.position?.y || 0) + deltaY
                    }
                    canvasStore.moveComponent(id, newPos)
                    canvasStore.updateComponent(id, {
                        style: {
                            ...comp.style,
                            left: `${newPos.x}px`,
                            top: `${newPos.y}px`
                        }
                    })
                }
            })
        }
    } else {
        // 单个组件移动
        canvasStore.moveComponent(componentId, position)
        canvasStore.updateComponent(componentId, {
            style: {
                ...canvasStore.canvasState.components.find(c => c.id === componentId)?.style,
                left: `${position.x}px`,
                top: `${position.y}px`
            }
        })
    }
}

// 处理组件大小调整
const handleComponentResize = (componentId, size) => {
    canvasStore.resizeComponent(componentId, size)
    canvasStore.updateComponent(componentId, {
        style: {
            ...canvasStore.canvasState.components.find(c => c.id === componentId)?.style,
            width: `${size.width}px`,
            height: `${size.height}px`
        }
    })
}

// 删除选中组件
const deleteSelectedComponents = () => {
    if (selectedComponentIds.value.length > 0) {
        canvasStore.removeSelectedComponents()
    }
}

// 键盘事件处理
const handleKeyDown = (event) => {
    if (event.key === 'Delete' || event.key === 'Backspace') {
        deleteSelectedComponents()
    }
}
</script>

<template>
    <div ref="canvasRef" class="canvas-area relative w-full min-h-full" @drop="handleDrop" @dragover="handleDragOver"
        @click="handleCanvasClick" @keydown="handleKeyDown" @mousedown="handleMouseDown" @mousemove="handleMouseMove"
        @mouseup="handleMouseUp" tabindex="0">
        <!-- 空状态提示 -->
        <div v-if="components.length === 0" class="absolute inset-0 flex items-center justify-center text-gray-400 pointer-events-none">
            <div class="text-center">
                <div class="text-6xl mb-4">📱</div>
                <div class="text-lg font-medium mb-2">开始构建你的界面</div>
                <div class="text-sm">从左侧拖拽组件到这里</div>
            </div>
        </div>

        <!-- 渲染组件 -->
        <RenderComponent v-for="component in components" :key="component.id" :component="component"
            :selected="selectedComponentIds.includes(component.id)" @click="handleComponentClick(component.id, $event)"
            @move="handleComponentMove(component.id, $event)" @resize="handleComponentResize(component.id, $event)" />
        
        <!-- 框选框 -->
        <div v-if="isSelecting" :style="selectionBoxStyle"></div>
    </div>
</template>

<style scoped>
.canvas-area:focus {
    outline: none;
}

/* 拖拽悬停效果 */
.canvas-area.drag-over {
    background-color: rgba(59, 130, 246, 0.05);
}
</style>
